package com.second.task;

import com.second.mapper.FCommentMapper;
import com.second.mapper.FCommentZanMapper;
import com.second.model.pojo.FComment;
import com.second.model.pojo.FCommentZan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Component
public class ZanTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FCommentMapper commentMapper;

    @Autowired
    private FCommentZanMapper commentZanMapper;

    @Scheduled(cron = "0/60 * * * * ? ")
    public void saveRedisZan(){
        List<FComment> commentList = commentMapper.findAll();
        for (FComment c : commentList) {
            Set<String> setsZan = redisTemplate.opsForSet().members("Zan:"+c.getId());
            Iterator<String> iterator = setsZan.iterator();
            while(iterator.hasNext()){
                String it = iterator.next();
                String[] ZanInfo = it.split("::");
                Integer userId = Integer.valueOf(ZanInfo[0]);
                Integer status = Integer.valueOf(ZanInfo[1]);
                //如果用户之前没有对评论操作过
                FCommentZan cZan = commentZanMapper.getByUserIdAndCommentId(userId,c.getId());
                if (null == cZan){
                    FCommentZan zan = new FCommentZan();
                    zan.setCommentId(c.getId());
                    zan.setUserId(userId);
                    zan.setStatus(status);
                    commentZanMapper.save(zan);
                }else {
                    cZan.setStatus(status);
                    commentZanMapper.save(cZan);
                }
            }

            Set<String> setsNotZan = redisTemplate.opsForSet().members("NotZan:"+c.getId());
            Iterator<String> iterator1 = setsNotZan.iterator();
            while(iterator1.hasNext()){
                String it = iterator1.next();
                String[] ZanInfo = it.split("::");
                Integer userId = Integer.valueOf(ZanInfo[0]);
                Integer status = Integer.valueOf(ZanInfo[1]);
                //如果用户之前没有对评论操作过
                FCommentZan cZan = commentZanMapper.getByUserIdAndCommentId(userId,c.getId());
                if (null == cZan){
                    FCommentZan zan = new FCommentZan();
                    zan.setCommentId(c.getId());
                    zan.setUserId(userId);
                    zan.setStatus(status);
                    commentZanMapper.save(zan);
                }else {
                    cZan.setStatus(status);
                    commentZanMapper.save(cZan);
                }
            }
        }
    }
}
